﻿using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using System.Drawing;
using XBLib.Dal.AdoDal; 

public partial class Org_frmO_EmpDivisionInput : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ((Org_MasterPage)this.Master).changeTitle("所属情報登録");
        ((Org_MasterPage)this.Master).HideLiArea("frmO_EmpDivisionInput");

		if (Session["人コード"] == null)
		{
			Response.Redirect("../frmD_Login.aspx");
		}
		else if (Session["人コード"].ToString() == "")
		{
			Response.Redirect("../frmD_Login.aspx");
		}

		if (Request.UrlReferrer != null)
		{
			string PageRequest = Request.UrlReferrer.ToString();

			if (PageRequest.IndexOf("frmO_EmpDegreeByCompInput.aspx") > 0 || PageRequest.IndexOf("frmO_EmpCareerInput.aspx") > 0)
			{
				if (Session["社員ID"] == null)
					Response.Redirect("../frm_MainMenu.aspx");
				else if (Session["社員ID"].ToString() == "")
					Response.Redirect("../frm_MainMenu.aspx");

				Session["Action_frmO_EmpDivisionInput"] = "insert";
			}
			if (PageRequest.IndexOf("frmO_EmpBasicInfo.aspx") > 0)
			{
				Session["Action_frmO_EmpDivisionInput"] = "update";

				btn登録.Text = "更新";
				btn_次.Visible = false;

				Session["flag"] = "1";
			}
		}
		else
		{
			if (Session["flag"] != null)
			{
				Session.Remove("flag");
				Response.Redirect("frmO_EmpBasicInfo.aspx");
			}
		}

		try
		{
			string id = "";

			if (Session["flag"] != null)
			{
				id = Request.QueryString["id"] != null ? Request.QueryString["id"] : "";
				ViewState["所属情報_社員ID"] = Int32.Parse(id);
			}
			else
			{
				ViewState["所属情報_社員ID"] = Int32.Parse(Session["社員ID"].ToString());
			}
		}
		catch
		{
			Response.Redirect("frmO_EmpBasicInfo.aspx");
		}


		if (!IsPostBack)
		{
			bind兼務();
			bind部門コード();
			bind役職コード();
			ddl_兼務.Focus();

			string ER00001 = GetError("ER00001");
			string ER00005 = GetError("ER00005");
			string ER00006 = GetError("ER00006");
			string ER00007 = GetError("ER00007");

			RequiredFieldValidator兼務.ErrorMessage = ER00007;
			CustomValidator発令開始日.ErrorMessage = ER00005;
			CustomValidator発令開始日1.ErrorMessage = ER00006;
			RequiredFieldValidator発令開始日.ErrorMessage = ER00001;
			CustomValidator発令終了日.ErrorMessage = ER00005;
			CustomValidator発令終了日1.ErrorMessage = ER00006;
			RequiredFieldValidator勤務地.ErrorMessage = ER00001;

			int 社員ID = Int32.Parse(ViewState["所属情報_社員ID"].ToString());
			LoadInfo_Reset所属情報(社員ID);
		}
    }
	protected void LoadInfo_Reset所属情報(int 社員ID)
	{
		所属情報Manager frm = new 所属情報Manager();
		DataTable dt = frm.select所属情報by社員ID(社員ID);
		if (dt.Rows.Count > 0)
		{
			ddl_兼務.SelectedValue = dt.Rows[0]["兼務"].ToString();
			ddl_部門名.SelectedValue = dt.Rows[0]["部門コード"].ToString() != "0###" ? dt.Rows[0]["部門コード"].ToString() : "-1";
			ddl_役職.Text = dt.Rows[0]["役職コード"].ToString() != "0" ? dt.Rows[0]["役職コード"].ToString() : "-1";
			txt_発令開始日.Text = DateTime.Parse(dt.Rows[0]["発令開始日"].ToString()).ToString("yyyy/MM/dd");
			txt_発令終了日.Text = dt.Rows[0]["発令終了日"].ToString() != "" ? DateTime.Parse(dt.Rows[0]["発令終了日"].ToString()).ToString("yyyy/MM/dd") : "";
			txt_勤務地.Text = dt.Rows[0]["勤務地"].ToString();

			btn登録.Text = "更新";
			Session["Action_frmO_EmpDivisionInput"] = "update";
		}
		else 
		{
			btn登録.Text = "登録";
			ddl_兼務.SelectedValue = "-1";
			ddl_部門名.SelectedValue = "-1";
			ddl_役職.SelectedValue = "-1";
			txt_発令開始日.Text = "";
			txt_発令終了日.Text = "";
			txt_勤務地.Text = "";
		}
	}
	protected void btn_戻る_Click(object sender, EventArgs e)
	{
		if(Session["flag"] != null)
			Session.Remove("flag");

		if (btn_次.Visible == false)
			Response.Redirect("frmO_EmpBasicInfo.aspx?id=" + ViewState["所属情報_社員ID"].ToString() + "#114");
		else
			Response.Redirect("frmO_EmpDegreeByCompInput.aspx");
	}
    protected void btn_次_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmO_EmpCareerInput.aspx");
    }

    /// <summary>
    /// load du lieu vao dropdownList 兼務
    /// </summary>
    public void bind兼務()
    {
        try
        {
            DataTable dt = new DataTable();
            DataColumn col;
            DataRow row;

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.Int32");
            col.ColumnName = "value";
            dt.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.String");
            col.ColumnName = "text";
            dt.Columns.Add(col);

            row = dt.NewRow();
            row["value"] = -1;
            row["text"] = "[選択]";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["value"] = 0;
            row["text"] = "主務";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["value"] = 1;
            row["text"] = "兼務";
            dt.Rows.Add(row);

            ddl_兼務.DataSource = dt;
            ddl_兼務.DataValueField = "value";
            ddl_兼務.DataTextField = "text";

            ddl_兼務.DataBind();
        }
        catch { }
    }

    /// <summary>
    /// load du lieu vao dropdownList 部門コード
    /// </summary>
    public void bind部門コード()
    {
        所属情報Manager frm = new 所属情報Manager();
        DataTable dt = frm.Select部門コード();
        ddl_部門名.DataSource = dt;
        ddl_部門名.DataTextField = "部門名";
        ddl_部門名.DataValueField = "ID";
        ddl_部門名.DataBind();

        ListItem 選択 = new ListItem("[選択]", "-1");
        ddl_部門名.Items.Insert(0, 選択);
    }

    /// <summary>
    /// load du lieu vao dropdownList 役職コード
    /// </summary>
    public void bind役職コード()
    {
        所属情報Manager frm = new 所属情報Manager();
        DataTable dt = frm.Select役職コード();
        ddl_役職.DataSource = dt;
        ddl_役職.DataTextField = "役職名";
        ddl_役職.DataValueField = "ID";
        ddl_役職.DataBind();

        ListItem 選択 = new ListItem("[選択]", "-1");
        ddl_役職.Items.Insert(0, 選択);
    }
    protected void btnリセット_Click(object sender, EventArgs e)
    {
		ResetForm();
    }
    protected void btn登録_Click(object sender, EventArgs e)
    {
        SetValueForControl();

        bool isValidate = true;

        所属情報 obj = new 所属情報();
        obj.社員ID = Int32.Parse(ViewState["所属情報_社員ID"].ToString());
        obj.廃止区分 = 0;

        if (ddl_部門名.SelectedValue != "-1")
        {
            string[] arr = new string[4];
            char[] splitter = { '#' };
            arr = ddl_部門名.SelectedValue.Split(splitter);

            obj.部門コード = Int32.Parse(arr[0]);
            obj.部門名 = arr[1];
            obj.部門英語名 = arr[2];
            obj.部門略称 = arr[3];
        }

        if (ddl_役職.SelectedValue != "-1")
        {
            obj.役職コード = Int32.Parse(ddl_役職.SelectedValue);
            obj.役職 = ddl_役職.SelectedItem.Text;
        }

        if (txt_発令終了日.Text.Length > 0)
        {
            if (DateTime.Parse(txt_発令終了日.Text) <= DateTime.Parse(txt_発令開始日.Text))
            {
                CustomValidator発令終了日.IsValid = false;
                return;
            }
            else
                obj.発令終了日 = DateTime.Parse(txt_発令終了日.Text);
        }

        if (isValidate == true)
        {
            obj.兼務 = Int32.Parse(ddl_兼務.SelectedValue);
            obj.発令開始日 = DateTime.Parse(txt_発令開始日.Text);
            obj.勤務地 = txt_勤務地.Text;

			所属情報Manager frm = new 所属情報Manager();

			if (btn登録.Text == "登録")
			{
				frm.Insert所属情報(obj);
				if(btn_次.Visible == true)
					Response.Redirect("frmO_EmpCareerInput.aspx");
				else
					ResetForm();
			}
			else
			{
				frm.Update所属情報(obj);
				ResetForm();
			}
			ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
        }
    }
	protected void ResetForm()
	{
		int 社員ID = Int32.Parse(ViewState["所属情報_社員ID"].ToString());
		LoadInfo_Reset所属情報(社員ID);
	}
   
    /// <summary>
    /// chuyen doi ki tu < >
    /// </summary>
    /// <param name="root"></param>
    /// <returns></returns>
    public static Control[] FlattenHierachy(Control root)
    {
        List<Control> list = new List<Control>();
        list.Add(root);
        if (root.HasControls())
        {
            foreach (Control control in root.Controls)
            {
                list.AddRange(FlattenHierachy(control));
            }
        }
        return list.ToArray();
    }
    protected void SetValueForControl()
    {
        Control[] allControls = FlattenHierachy(Page);
        foreach (Control control in allControls)
        {
            TextBox textBox = control as TextBox;
            if (textBox != null)
            {
                textBox.Text = textBox.Text.Replace("<", "&lt;");
                textBox.Text = textBox.Text.Replace(">", "&gt;");
            }
        }
    }

    /// <summary>
    /// ham lay loi tu database
    /// </summary>
    /// <param name="errorid"></param>
    /// <returns></returns>
    public String GetError(string errorid)
    {
        string error = "";
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        if (dt.Rows.Count > 0)
            error = dt.Rows[0][2].ToString();
        return error;
    }
}
